package com.tangly.codeing.service.impl;

import com.tangly.codeing.dao.SysRolePrivilegeDao;
import com.tangly.codeing.model.SysRolePrivilege;
import com.tangly.codeing.model.SysUserRole;
import com.tangly.codeing.model.dto.SysRoleDto;
import com.tangly.codeing.service.SysRolePrivilegeService;
import com.tangly.codeing.utils.PageInfo;
import com.tangly.codeing.utils.ReturnT;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色权限表
 *
 * @author tangbing
 * @date 2019-05-30
 */
@Service
public class SysRolePrivilegeServiceImpl implements SysRolePrivilegeService {

    @Resource
    private SysRolePrivilegeDao sysRolePrivilegeDao;

    /**
     * 新增
     */
    @Override
    public ReturnT<String> insert(SysRolePrivilege sysRolePrivilege) {

        // valid
        if (sysRolePrivilege == null) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "必要参数缺失");
        }

        sysRolePrivilegeDao.insert(sysRolePrivilege);
        return ReturnT.SUCCESS;
    }

    /**
     * 删除
     */
    @Override
    public ReturnT<String> delete(Long id) {
        int ret = sysRolePrivilegeDao.delete(id);
        return ret > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
    }

    /**
     * 批量删除
     */
    @Override
    public ReturnT<String> batchDelete(List<String> ids) {
        int ret = sysRolePrivilegeDao.batchDelete(ids);
        return ret > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
    }

    /**
     * 更新
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> update(SysRoleDto sysRoleDto) {
        // 更新用户角色信息
        List<Long> perIdList = sysRoleDto.getPermissions();
        List<SysRolePrivilege> sysRolePrivileges = new ArrayList<>();
        perIdList.forEach(permId -> sysRolePrivileges.add(new SysRolePrivilege(sysRoleDto.getRoleId(), permId)));
        sysRolePrivilegeDao.delete(sysRoleDto.getRoleId());
        sysRolePrivilegeDao.saveOrUpdate(sysRolePrivileges);
        return ReturnT.SUCCESS;
    }

    /**
     * Load查询
     */
    @Override
    public SysRolePrivilege load(Long id) {
        return sysRolePrivilegeDao.load(id);
    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo pageList(PageInfo pageInfo) {

        List<SysRolePrivilege> pageList = sysRolePrivilegeDao.pageList(pageInfo);
        int totalCount = sysRolePrivilegeDao.pageListCount(pageInfo);

        pageInfo.setResultObject(pageList);
        pageInfo.setTotalRecord(totalCount);
        return pageInfo;
    }

}
